#include <iostream>
#include <stdexcept>
#include <exception>
#include <string>
#include <vector>
#include "SDL.h"
#include "SDL_image.h"
#include "sdlbutton.h"
#include "sdltext.h"
#include "character.h"
#include "inventorywindow.h"
#include "gamemenu.h"
using namespace std;

GameMenu::GameMenu(class Character *character) throw(gamemenu_error)
{
       menuBackground_ = NULL;
       invButton_ = NULL;
       exitButton_ = NULL;
       inWindow_ = NULL;
       character_ = character;
       inventoryWindowVisible = false;

       // Load menu background
       menuBackground_ = IMG_Load("adventure2/graphics/backdrops/gamemenub.png");
       if(menuBackground_ == NULL)
       {
	      throw gamemenu_error("Could not load adventure2/graphics/backdrops/gamemenub.png");
       }

       menuBackgroundRect_.h = menuBackground_->h;
       menuBackgroundRect_.w = menuBackground_->w;
       menuBackgroundRect_.x = 0;
       menuBackgroundRect_.y = 688;
              
       try
       {
	      // Load the text
	      itemButtonText_ = new SDLText(255, 255, 255, 20, "CHECKBK0.TTF", "Inventory");
	      exitButtonText_ = new SDLText(255, 255, 255, 20, "CHECKBK0.TTF", "Exit");
	      hpText_ = new SDLText(495, 20, 255, 255, 255, 20, "CHECKBK0.TTF", "HP: 100");
	      
	      // Load pictures for the button
	      invButton_ = new SDLButton("unew_game.png", "cnew_game.png", 10, 20, menuBackground_, itemButtonText_);
	      exitButton_ = new SDLButton("unew_game.png", "cnew_game.png", 914, 20, menuBackground_, exitButtonText_);

	      // Load inventory window
	      inWindow_ = new InventoryWindow(character);
       }
       catch(sdlbutton_error &error)
       {
	      cout << error.what();
	      abort();
       }
       catch(sdltext_error &error)
       {
	      cout << error.what();
	      abort();
       }
       catch(inventory_error &error)
       {
	      cout << error.what();
	      abort();
       }
}

GameMenu::~GameMenu()
{
       SDL_FreeSurface(menuBackground_);
       delete invButton_;
       delete exitButton_;
       delete itemButtonText_;
       delete exitButtonText_;
       delete inWindow_;
}

void GameMenu::is_clicked(int x, int y, class SDLMap *map)
{
       if(invButton_->is_clicked(x, y-688) == true)
       {
	      inWindow_->show();
	      inventoryWindowVisible = true;
       }
       exitButton_->is_clicked(x, y-688);
       inWindow_->is_clicked(x, y, inventoryWindowVisible, map);       
}

void GameMenu::render(struct SDL_Surface *screen)
{
       // Render Health Points
       hpText_->set_text("HP: 100");
       hpText_->render(menuBackground_);

       invButton_->render();
       exitButton_->render();

       inWindow_->render(screen);

       SDL_BlitSurface(menuBackground_, NULL, screen, &menuBackgroundRect_);
}

bool GameMenu::inventoryVisible() const
{
       return inventoryWindowVisible;
}
